package com.chapter7;

/**
 * @author chenxd
 * @version V1.0
 * @Package com.chapter7
 * @Description: (用一句话描述该文件做什么)
 * @date 2018/8/26 10:54
 */
@SuppressWarnings("all")
public class TicketWindowRunnable implements Runnable {

    //共享数据
    private int index = 1;

    //只读的共享数据
    private final static int max = 500;

    private final Object monitor = new Object();

    /**
     * 1 同步代码块
     */
    /*@Override
    public void run() {
        while (true){//(index <= max) {

            synchronized (monitor) {//现在线程争抢的锁是 monitor
                if (index > max) {
                    break;
                }

                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread() + "的号码是" + (index++));
             }

        }
    }*/

    /**
     * 2 同步方法
     */
    /*@Override
    public synchronized void run() { //现在线程争抢的锁是this，当前类的实例
        while (true) {//(index <= max) {
            if (index > max) {
                break;
            }

            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread() + "的号码是" + (index++));
        }
    }*/

    /**
     * 针对1的代码优化， 也就是将代码块分离出来
     */
    @Override
    public void run() { //现在线程争抢的所是this，当前类的实例
        while (true) {//(index <= max) {
            if (ticket()) {
                break;
            }
        }
    }

    protected synchronized boolean ticket(){
        if(index > max){
            return true;
        }
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + "的号码是" + (index++));
        return false;
    }
}
